<template>
    <el-row class="forbid-select main-page full-in-main">
        <el-col :span="1" v-if="!mobile"/>
        <el-col :span="19" class="note_main">
            <div :key="key" class="note_body animate__animated animate__fadeInLeft" style="touch-action: none">
                <el-scrollbar style="height: 100%;width: 100%;touch-action: none" v-loading="loading"
                              element-loading-delay=200 ref="scrollbarRef">
                    <div v-for="(item, index) in data" :key="index" class="note_info" v-show="item.sequence"
                         @click="intoNoteDetail(item.sequence)">
                        <el-row>
                            <el-col :span="6" class="note_img" v-if="!mobile">
                                <el-image :src="item.titleImage || defaultImage" style="height: 150px;padding: 20px"
                                          loading="lazy" v-if="!mobile"/>
                            </el-col>
                            <el-col :span="18" class="note_desc">
                                <el-row class="title_row">
                                    <span class="note_title ">
                                        <span class="note_type">
                                            [{{ item.sourceType === 0 ? '转载' : '原创' }}]
                                        </span>
                                        <span>{{ item.title }}</span>
                                    </span>
                                </el-row>
                                <el-row class="description">
                                    <div class="description_content">
                                        {{ item.description }}
                                    </div>
                                </el-row>
                                <el-row class="note_footer untouchable">
                                    <el-scrollbar class="full-percent">
                                        <div class="note_footer-content">
                                            <span style=" padding-right: 5px">
                                                {{ item.crtTime }}
                                            </span>
                                            <span @click.stop="showByType(item.type)" class="cursor-pointer">
                                                {{ item.type }}
                                            </span>
                                            <span v-for="(tag, index) in item.tag.split(',')" :key="index"
                                                  class="cursor-pointer" style="margin: 0 5px"
                                                  @click.stop="showByTag(tag)" v-if="item.tag">
                                                #{{ tag }}
                                            </span>
                                        </div>
                                    </el-scrollbar>
                                </el-row>
                            </el-col>
                        </el-row>
                    </div>
                    <div v-if="mobile" class="load">
                        <div class="load-more" @click="loadMore" v-if="showLoadMore">
                            加载更多
                        </div>
                    </div>
                    <el-pagination v-model:current-page="page" :page-size="limit" background
                                   layout="prev, pager, next"
                                   :total="total" @current-change="handleCurrentChange" v-else-if="showPagination"
                                   hide-on-single-page/>
                </el-scrollbar>
            </div>
        </el-col>
        <el-col :span="3" class="category_body" v-if="!mobile">
            <div class="animate__animated animate__fadeInLeft">
                <div class="type-body">
                    <el-scrollbar style="width: 100%;height: 100%">
                        <div v-for="(item, index) in typeCount" :key="index" style="padding: 5px 10px"
                             :class="`type_${index} desc cursor-pointer ${current === item.name && current !== allText ? 'selected' : ''}`"
                             @click.stop="showByType(item.name)">
                            <div style="display: flex">
                                <div style="width: 200px;">{{ item.name }}</div>
                                <div>{{ item.num }}</div>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
                <div class="tag-body">
                    <el-scrollbar style="width: 100%;height: 100%">
                        <div v-for="(item, index) in tagCount" :key="index" style="padding: 5px 10px"
                             @click="showByTag(item.name)"
                             :class="`tag_${index} desc cursor-pointer ${current === ('#' + item.name) ? 'selected' : ''}`">
                            <div style="display: flex">
                                <div style="width: 200px;">{{ item.name }}</div>
                                <div>{{ item.num }}</div>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </el-col>
        <el-col :span="1" v-if="!mobile"/>
        <el-drawer :show-close="false" :with-header="false" size="200px" v-model="showTagType" direction="rtl"
                   class="menu-drawer forbid-select" modal-class="untouchable">
            <div class="type-body">
                <el-scrollbar style="width: 100%;height: 100%">
                    <div v-for="(item, index) in typeCount" :key="index" style="padding: 5px 10px"
                         :class="`type_${index}`" @click.stop="showByType(item.name)"
                         :style="`background:${current === item.name && current !== allText ? '#aaaaaa' : ''}`">
                        <div style="display: flex">
                            <div style="width: 150px;">{{ item.name }}</div>
                            <div>{{ item.num }}</div>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
            <div class="tag-body">
                <el-scrollbar style="width: 100%;height: 100%">
                    <div v-for="(item, index) in tagCount" :key="index" style="padding: 5px 10px"
                         @click="showByTag(item.name)"
                         :style="`background:${current === ('#' + item.name) ? '#aaaaaa' : ''}`"
                         :class="`tag_${index}`">
                        <div style="display: flex">
                            <div style="width: 150px;">{{ item.name }}</div>
                            <div>{{ item.num }}</div>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
        </el-drawer>

        <el-icon v-if="mobile" class="menu-icon" @click="showTagType = !showTagType">
            <component :is="getIcon('Grid')"/>
        </el-icon>
    </el-row>
</template>

<script setup>
import {useRequest, useTouch, useCheckScrollToBottom} from "@usehook"
import router from "@/router"
import {getIcon, mobile} from "@/utils/tools"

const defaultImage = "https://dmp.dansj.cn/file/get/dmp/c4e1e3fe9a98475db7d5dcc06b564a99?sign=mPuoumkCityFaPfvfNXOBbC&preview&cache"

let data = $ref([])

let typeCount = $ref([])
let typeMap = $ref([])
let tagCount = $ref([])
let tagMap = $ref([])
let key = $ref(0)
let current = $ref("")
let loading = $ref(false)
let page = $ref(1)
let limit = $ref(20)
let total = $ref(0)
let allText = '全部笔记'
const scrollbarRef = ref(null)

const showPagination = computed(() => {
    return data.length > 0 && !loading
})

useCheckScrollToBottom(computed(() => scrollbarRef.value.wrapRef), () => {
    if (showLoadMore.value && !loading && mobile) loadMore()
})

const showLoadMore = computed(() => {
    return (data.length > 0 && !loading && data.length < total) || loading
})

const handleCurrentChange = (currentPage) => {
    page = currentPage
    key = new Date().getTime()
    const query = router.currentRoute.value.query
    if (currentPage > 1) {
        router.replace({query: {...query, pageNum: page}})
    } else {
        const {pageNum, ...newQuery} = query
        router.replace({query: {...newQuery}})
    }
    getData()
}

const loadMore = () => {
    page++
    getData(true)
}

const updateCurrentTagType = () => {
    const query = router.currentRoute.value.query
    const hasTag = query.hasOwnProperty("tag")
    const hasCategory = query.hasOwnProperty("category")
    const tag = query.tag
    const category = query.category
    current = hasTag ? "#" + tag : hasCategory ? category : ''
    if (hasTag) scrollIntoView("tag", tag)
    if (hasCategory) scrollIntoView("type", category)
}

const getData = (append = false) => {
    const query = router.currentRoute.value.query
    const value = query.hasOwnProperty("tag") ? query.tag : query.hasOwnProperty("category") ? query.category : ''
    const key = query.hasOwnProperty("tag") ? "tag" : "category"
    const params = {page, limit, [key]: value}

    if (!append) data = []
    loading = true
    useRequest({url: "/article/getList", ...params}).then(resp => {
        if (resp && resp.status) {
            if (append) {
                data.push(...resp.data)
            } else {
                data = resp.data
            }
            total = resp.totalRecord
        }
    }).finally(() => {
        loading = false
    })
}

const intoNoteDetail = (sequence) => {
    router.push("/note/detail?sequence=" + sequence)
}

const showByType = async (type) => {
    scrollIntoView('type', type)
    if (current === type || (current === '' && type === allText)) return
    current = type
    key = new Date().getTime()
    page = 1
    await useRouteQuery({category: type})
    getData()
    showTagType = false
}

const scrollIntoView = (lx, name) => {
    const className = lx === 'tag' ? '.tag_' + tagMap.indexOf(name) : '.type_' + typeMap.indexOf(name)
    const querySelector = document.querySelector(className)
    if (querySelector) querySelector.scrollIntoView({behavior: "smooth"})
}

const showByTag = async (tag) => {
    scrollIntoView('tag', tag)
    if (current === '#' + tag) return
    current = "#" + tag
    key = new Date().getTime()
    page = 1
    await useRouteQuery({tag})
    getData()
    showTagType = false
}

const useRouteQuery = async (params) => {
    if (Object.values(params)[0] === '全部笔记') {
        await router.replace({query: {}})
    } else {
        await router.replace({query: {...params}})
    }
}

let showTagType = $ref(false)

useTouch(() => showTagType = true, "right")

onMounted(async () => {
    page = router.currentRoute.value.query.hasOwnProperty("pageNum") ? parseInt(router.currentRoute.value.query.pageNum) : 1
    getData()
    await useRequest({url: "/article/category"}).then(resp => {
        if (resp && resp.status) {
            let total = 0
            typeCount = resp.data
            typeMap = typeCount.map(e => {
                return e.name
            })
            for (let item of resp.data) {
                total += item.num
            }
            typeCount.unshift({name: allText, num: total})
        }
    })

    await useRequest({url: "/article/tagCount"}).then(resp => {
        if (resp && resp.status) {
            tagCount = resp.data
            tagMap = tagCount.map(e => {
                return e.name
            })
        }
    })

    updateCurrentTagType()
})
</script>

<style lang="scss" scoped>
:deep(.el-scrollbar__bar.is-vertical),
:deep(.el-scrollbar__bar.is-horizontal) {
    display: none !important;
}

:deep(.note_body) {
    padding: 10px;
    width: calc(100% - 20px);
    height: calc(100vh - 90px);
}

.mobile .note_body {
    height: calc(100% - 20px) !important;
    width: calc(100% - 20px);
    padding: 10px;
}

.mobile .note_main {
    min-width: 100%;
}

.mobile .note_title {
    width: 100%;
    line-height: 25px;
}

:deep(.note_type) {
    color: rgb(0 135 255);
    padding: 0 10px 0 0;
}

.dark .note_type {
    color: rgb(158 255 157);
}

.mobile .note_type {
    min-width: 55px;
    color: rgb(0 63 255);
    line-height: 25px;
}

:deep(.title_row) {
    position: static;
    width: 100%
}

.mobile .title_row {
    position: static;
    padding: 5px 0;
}

:deep(.note_info) {
    width: calc(100% - 10px);
    margin-top: 10px;
    padding: 5px;
    border-radius: var(--border-radius);
    background: var(--background);
    position: relative;
}

.mobile .note_info {
    height: fit-content;
}

.mobile .category_body {
    display: none;
}

:deep(.note_info:first-child) {
    margin-top: 0;
}

:deep(.note_desc) {
    padding: 0 10px;
    position: relative;
}

.mobile .note_desc {
    width: 100%;
    min-width: 100%;
}

:deep(.description) {
    padding: 10px 0;
}

.mobile .description {
    line-height: 25px;
    position: static;
    padding: 0;
    background: rgb(255 255 255 / 10%);
    border-radius: 3px;
}

.mobile .description_content {
    padding: 5px 10px;
}

:deep(.note_footer-content) {
    text-wrap: nowrap;
}

:deep(.note_footer) {
    position: absolute;
    bottom: 5px;
    width: calc(100% - 20px);
    height: calc(var(--font-size) + 5px);
}

.mobile .note_footer {
    width: 100%;
    height: 100%;
    text-wrap: nowrap;
    position: static;
    padding: 5px 0;
    overflow-y: auto !important;

}

:deep(.type-body) {
    padding: 5px;
    height: 290px;
    background: var(--background);
    margin: 10px 0;
    border-radius: var(--border-radius)
}

:deep(.tag-body) {
    background: var(--background);
    margin: 10px 0;
    height: calc(100vh - 410px);
    border-radius: var(--border-radius);
    padding: 5px;
}

:deep(.el-pagination) {
    justify-content: center;
    align-items: center;
    padding: 15px 0 5px 0;
}

.mobile .note_img {
    display: none;
}

.mobile .type-body {
    height: 30%;
    margin: 5px 0
}

.mobile .tag-body {
    height: calc(70% - 15px);
    margin: 5px 0;
}

:deep(.menu-drawer.el-drawer .el-drawer__body) {
    padding: 0 5px !important;
}

.menu-icon {
    position: absolute;
    bottom: 5px;
    right: 5px;
    font-size: 25px;
    background: #b9b9b9;
    padding: 5px;
    border-radius: 50%;
    color: bisque;
    box-shadow: 0 0 0.61538462em rgba(0, 0, 0, 0.4);
}

.load-more {
    font-size: 16px;
    background: rgb(255 255 255 / 60%);
    border-radius: 5px;
    padding: 5px 15px;
    width: 65px;
    margin: 0 auto;
}

:deep(.load:has(.load-more)) {
    padding-top: 10px;
}

.selected {
    background: rgb(45 45 45 / 10%);
    transition: background .2s;
    border-radius: 2px;
}

.desc{
    transition: background .2s;
}
</style>